package juc.popular;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 基于散列链表+红黑树实现,类似于 HashMap,无序
 * JDK 8 进行了优化,利用 volatile + CAS 实现无锁化操作,保证线程安全的同时,提高性能
 *
 * @author 王霄
 * @date 2021/9/20 09:59
 */
public class ConcurrentHashMapDemo {

    public static void main(String[] args) throws InterruptedException {
        Map<String, Integer> map = new ConcurrentHashMap<>();
        Task t1 = new Task(map), t2 = new Task(map), t3 = new Task(map);
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
        System.out.println(map);
    }

    public static class Task extends Thread {
        private final Map<String, Integer> map;

        public Task(Map<String, Integer> map) {
            this.map = map;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                map.compute("count", (k, v) -> Optional.ofNullable(v)
                        .map(x -> x + 1).orElse(1));
            }
        }
    }

}
